﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace FPSO.Services.Utils
{
    public class DbRepository<T> where T : class, new()
    {
        public DbRepository()
        {
        }

        protected void InsertEntity(T val)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            sugarClient.Insertable(val).ExecuteCommand();
        }

        protected void UpdateEntity(T val)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            sugarClient.Updateable(val).ExecuteCommand();
        }

        protected List<T> QueryListByCondition(string condition)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            return sugarClient.Queryable<T>().Where(condition).ToList();
        }

        protected List<T> QueryListByCondition(string condition, string orderby)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            return sugarClient.Queryable<T>().Where(condition).OrderBy(orderby).ToList();
        }

        protected List<T> QueryListByCondition(Expression<Func<T, bool>> condiitonExpr)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            return sugarClient.Queryable<T>().Where(condiitonExpr).ToList();
        }

        protected T QueryEntity(Expression<Func<T, bool>> conditionExpr)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            return sugarClient.Queryable<T>().Where(conditionExpr).First();
        }
        protected int QueryCount(Expression<Func<T, bool>> conditionExpr)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            return sugarClient.Queryable<T>().Where(conditionExpr).Count();
        }

        protected void DeleteById(int id)
        {
            SqlSugarClient sugarClient = CreateSqlSugarClient();
            sugarClient.Deleteable<T>().In(id).ExecuteCommand();
        }


		//FlushEntitys清空当前数据表中的数据，由IsBackup判断是否需要备份
		protected void FlushEntitys()
		{
			SqlSugarClient sugarClient = CreateSqlSugarClient();
			sugarClient.Deleteable<T>().ExecuteCommand();
		}

		protected SqlSugarClient CreateSqlSugarClient()
        {
            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConfigurationManager.AppSettings["MySQLStr"],
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {};
            });
        }

    }
}
